package com.upsuns.protocol;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.upsuns.utils.Constants;

/**
 *@Description:<p>协议接收端</p>
 *@author 王旭
 *@time 2016-2-9 下午10:03:07
 */
public class ProtocolServer {
	
	private int port; //监听端口
	
	private ServerSocket server;
	
	
	public ProtocolServer() {
		this.port = Constants.PORT_BASE - 1; //默认协议端口
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("创建服务失败");
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 接收protocol对象的序列化流，并反序列化。
	 * @return Protocol
	 */
	public Protocol receiveProtocol() {
		Protocol p = null;
		InputStream in = null;
		ObjectInputStream ois = null;
		try {
			Socket socket = server.accept();
			in = socket.getInputStream();
			ois = new ObjectInputStream(in);
			
			p = (Protocol) ois.readObject();
			
		} catch (IOException | ClassNotFoundException e) {
			System.out.println("协议接收失败");
			e.printStackTrace();
		} finally {
			try {
				ois.close();
				in.close();
				server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		return p;
	}


	public int getPort() {
		return port;
	}


	public void setPort(int port) {
		this.port = port;
	}


	public ServerSocket getServer() {
		return server;
	}


	public void setServer(ServerSocket server) {
		this.server = server;
	}
	

}
